/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.biz.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.csvreader.CsvWriter;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.FileUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportCSV;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.modules.biz.dao.BizBuyingRequisitionDao;
import com.thinkgem.jeesite.modules.biz.entity.*;
import com.thinkgem.jeesite.modules.biz.service.*;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.utils.LogUtils;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.common.utils.StringUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * 请购单的controllerController
 * @author xuchen
 * @version 2018-07-28
 */
@Controller
@RequestMapping(value = "${adminPath}/biz/bizBuyingRequisition")
public class BizBuyingRequisitionController extends BaseController {

	private static Logger log = LoggerFactory.getLogger(ExportExcel.class);

	@Autowired
	private BizBuyingRequisitionService bizBuyingRequisitionService;
	@Autowired
	private BizGoodsBrandService bizGoodsBrandService;
	@Autowired
	private BizSupplierService bizSupplierService;
	@Autowired
	private BizStorageService bizStorageService;
	@Autowired
	private BizBuyingRequisitionDetailService bizBuyingRequisitionDetailService;
	@Autowired
	private BizGoodsService bizGoodsService;
	@Autowired
	private BizBuyingRequisitionDao bizBuyingRequisitionDao;
	
	@ModelAttribute
	public BizBuyingRequisition get(@RequestParam(required=false) String buyingId) {
		BizBuyingRequisition entity = null;
		if (StringUtils.isNotBlank(buyingId)){
			entity = bizBuyingRequisitionService.get(buyingId);
		}
		if (entity == null){
			entity = new BizBuyingRequisition();
		}
		return entity;
	}
	
	@RequiresPermissions("biz:bizBuyingRequisition:view")
	@RequestMapping(value = {"list", ""})
	public String list(BizBuyingRequisition bizBuyingRequisition, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<BizBuyingRequisition> page = bizBuyingRequisitionService.findPage(new Page<BizBuyingRequisition>(request, response), bizBuyingRequisition); 
		model.addAttribute("page", page);
		return "modules/biz/bizBuyingRequisitionList";
	}




	@RequiresPermissions("biz:bizBuyingRequisition:view")
	@RequestMapping(value = "form")
	public String form(BizBuyingRequisition bizBuyingRequisition, Model model) {
		if (bizBuyingRequisition != null && StringUtils.isNotEmpty(bizBuyingRequisition.getBuyingId())){
			BizBuyingRequisition bizBuyingRequisition1 = bizBuyingRequisitionService.get(bizBuyingRequisition.getBuyingId());
			bizBuyingRequisition = bizBuyingRequisition1;
		}
		model.addAttribute("bizBuyingRequisition", bizBuyingRequisition);
		BizGoods bizGoods = new BizGoods();
		model.addAttribute("bizGoods",bizGoods );
		//获取全部的商品品牌
		List<BizGoodsBrand> bizGoodsBrandList = bizGoodsBrandService.findAllList(new BizGoodsBrand());
		//供应商--审批成功的
		BizSupplier bizSupplier = new BizSupplier();
		bizSupplier.setAppState("15");
		bizSupplier.setIsEnable("1");
		List<BizSupplier> bizSupplierList = bizSupplierService.findList(bizSupplier);
		//仓库
		List<BizStorage> bizStorageList = bizStorageService.findList(new BizStorage());
		//采购单的明细
		if(null != bizBuyingRequisition && StringUtils.isNotEmpty(bizBuyingRequisition.getBuyingId())){
			BizBuyingRequisitionDetail bizBuyingDetail = new BizBuyingRequisitionDetail();
			bizBuyingDetail.setBuyingId(bizBuyingRequisition.getBuyingId());
			List<BizBuyingRequisitionDetail> bizBuyingRequisitionList = bizBuyingRequisitionDetailService.findList(bizBuyingDetail);
			model.addAttribute("bizBuyingRequisitionList",bizBuyingRequisitionList);
			model.addAttribute("bizBuyingRequisitionCount",bizBuyingRequisitionList.size());
		}
		model.addAttribute("bizGoodsBrandList",bizGoodsBrandList);
		model.addAttribute("bizSupplierList",bizSupplierList);
		model.addAttribute("bizStorageList",bizStorageList);
		return "modules/biz/bizBuyingRequisitionForm";
	}

	@RequiresPermissions(value={"biz:bizBuyingRequisition:edit","biz:bizBuyingRequisition:add"},logical= Logical.OR)
	@RequestMapping(value = "save")
	public String save(BizBuyingRequisition bizBuyingRequisition, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, bizBuyingRequisition)){
			return form(bizBuyingRequisition, model);
		}
		bizBuyingRequisitionService.save(bizBuyingRequisition);
		addMessage(redirectAttributes, "保存请购单成功");
		return "redirect:"+Global.getAdminPath()+"/biz/bizBuyingRequisition/?repage";
	}
	
	@RequiresPermissions("biz:bizBuyingRequisition:remove")
	@RequestMapping(value = "delete")
	public String delete(BizBuyingRequisition bizBuyingRequisition, RedirectAttributes redirectAttributes) {
		bizBuyingRequisitionService.delete(bizBuyingRequisition);
		if(bizBuyingRequisition != null && StringUtils.isNotEmpty(bizBuyingRequisition.getBuyingId())){
			bizBuyingRequisitionDetailService.deleteByBuyingId(bizBuyingRequisition.getBuyingId());
		}
		addMessage(redirectAttributes, "删除请购单成功");
		return "redirect:"+Global.getAdminPath()+"/biz/bizBuyingRequisition/?repage";
	}

	@RequiresPermissions("biz:bizBuyingRequisition:toExamine")
	@RequestMapping(value = "toExamine")
	public String toExamine(BizBuyingRequisition bizBuyingRequisition, RedirectAttributes redirectAttributes) {
		String msg = "审批失败";
		if (bizBuyingRequisition != null && StringUtils.isNotEmpty(bizBuyingRequisition.getBuyingId())){
			bizBuyingRequisitionService.toExamine(bizBuyingRequisition.getBuyingId());
			msg = "审批成功";
		}
		addMessage(redirectAttributes, msg);
		return "redirect:"+Global.getAdminPath()+"/biz/bizBuyingRequisition/?repage";
	}

	@RequiresPermissions("biz:bizBuyingRequisition:reject")
	@RequestMapping(value = "reject")
	public String reject(BizBuyingRequisition bizBuyingRequisition, RedirectAttributes redirectAttributes) {
		String msg = "驳回失败";
		if(bizBuyingRequisition != null && StringUtils.isNotEmpty(bizBuyingRequisition.getBuyingId())){
			bizBuyingRequisitionService.reject(bizBuyingRequisition.getBuyingId());
			msg = "驳回成功";
		}
		addMessage(redirectAttributes, msg);
		return "redirect:"+Global.getAdminPath()+"/biz/bizBuyingRequisition/?repage";
	}

	@RequiresPermissions("biz:bizBuyingRequisition:resubmit")
	@RequestMapping(value = "resubmit")
	public String resubmit(BizBuyingRequisition bizBuyingRequisition, RedirectAttributes redirectAttributes) {
		String msg = "提交失败";
		if(bizBuyingRequisition != null && StringUtils.isNotEmpty(bizBuyingRequisition.getBuyingId())){
			bizBuyingRequisitionService.resubmit(bizBuyingRequisition.getBuyingId());
			msg = "提交成功";
		}
		addMessage(redirectAttributes, msg);
		return "redirect:"+Global.getAdminPath()+"/biz/bizBuyingRequisition/?repage";

	}

	@RequiresPermissions("biz:bizBuyingRequisition:submit")
	@RequestMapping(value = "submit")
	public String submit(BizBuyingRequisition bizBuyingRequisition, RedirectAttributes redirectAttributes) {
		String msg = "提交失败";
		if(bizBuyingRequisition != null && StringUtils.isNotEmpty(bizBuyingRequisition.getBuyingId())){
			bizBuyingRequisitionService.submit(bizBuyingRequisition.getBuyingId());
			msg = "提交成功";
		}
		addMessage(redirectAttributes, msg);
		return "redirect:"+Global.getAdminPath()+"/biz/bizBuyingRequisition/?repage";
	}


	/**
	 * 请购单快捷采购
	 * @param bizBuyingRequisition
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("biz:bizBuyingRequisition:quicklyCreatePurOrders")
	@RequestMapping(value = "quicklyCreatePurOrders")
	public String quicklyCreatePurOrders(BizBuyingRequisition bizBuyingRequisition,Model model, RedirectAttributes redirectAttributes) {
		if(bizBuyingRequisition != null && StringUtils.isNotEmpty(bizBuyingRequisition.getBuyingId())){
			//查询请购单单的明细
			ArrayList<BizBuyingRequisitionDetail> arrayList = new ArrayList<>();
			BizBuyingRequisitionDetail bizBuyingRequisitionDetail = new BizBuyingRequisitionDetail();
			bizBuyingRequisitionDetail.setBuyingId(bizBuyingRequisition.getBuyingId());
			List<BizBuyingRequisitionDetail>  bizBuyingRequisitionDetails = bizBuyingRequisitionDetailService.findList(bizBuyingRequisitionDetail);
			if(bizBuyingRequisitionDetails != null && bizBuyingRequisitionDetails.size() > 0){
				for (BizBuyingRequisitionDetail buyingRequisitionDetail : bizBuyingRequisitionDetails) {
					Integer minPurchaseQuantity = buyingRequisitionDetail.getMinPurchaseQuantity();//最小起购数量
					Integer surplusExpertAmount = buyingRequisitionDetail.getSurplusExpertAmount();//可请购数量
					if(minPurchaseQuantity != null && surplusExpertAmount != null){
						if(surplusExpertAmount == 0 || surplusExpertAmount < minPurchaseQuantity){
							arrayList.add(buyingRequisitionDetail);
						}
					}
				}
			}
			for (BizBuyingRequisitionDetail buyingRequisitionDetail : arrayList) {
				bizBuyingRequisitionDetails.remove(buyingRequisitionDetail);
			}
			model.addAttribute("bizBuyingRequisitionDetails",bizBuyingRequisitionDetails);
			model.addAttribute("bizPurchaseDetailCount",bizBuyingRequisitionDetails.size());
		}
		BizPurchase bizPurchase = new BizPurchase();
		bizPurchase.setPurchaseType(bizBuyingRequisition.getType());
		model.addAttribute("bizPurchase",bizPurchase);
		model.addAttribute("bizBuyingRequisition",bizBuyingRequisition);
		return "modules/biz/bizBuyingToPurchaseForm";
	}

	/**
	 * 通知快速请购 从通知页面的快捷采购按钮
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	/*@RequestMapping(value = "addAlertform")
	public String addAlertform(Model model, HttpServletRequest request, HttpServletResponse response) {
		BizBuyingRequisition bizBuyingRequisition = new BizBuyingRequisition();
		model.addAttribute("bizBuyingRequisition", bizBuyingRequisition);
		BizGoods bizGoods = new BizGoods();
		model.addAttribute("bizGoods",bizGoods );
		//警戒商品
		List<BizGoods> allWarningGoodsList = bizGoodsService.findAllWarningGoodsList(bizGoods);
		List<BizBuyingRequisitionDetail> bizBuyingList = new ArrayList<>();
		for (BizGoods goods : allWarningGoodsList) {
			//请购单的明细
			BizBuyingRequisitionDetail requisitionDetail = new BizBuyingRequisitionDetail();
			requisitionDetail.setGoodsId(goods.getGoodsId().toString());
			requisitionDetail.setGoodsName(goods.getGoodsName());
			requisitionDetail.setSupplierId(goods.getSupplierId());
			requisitionDetail.setSupplierName(goods.getSupplierName());
			requisitionDetail.setGoodsCategoryId(goods.getGoodsCategoryId());
			requisitionDetail.setGoodsCategoryName(goods.getGoodsCategoryName());
			requisitionDetail.setStockAmount(goods.getStockAmount().toString());
			requisitionDetail.setPurchasingAmount(goods.getPurchasingAmount().toString());
			requisitionDetail.setWarningAmount(goods.getWarningAmount().toString());
			bizBuyingList.add(requisitionDetail);
		}

		model.addAttribute("bizBuyingRequisitionList",bizBuyingList);
		model.addAttribute("bizBuyingRequisitionCount",bizBuyingList.size());
		return "modules/biz/bizBuyingRequisitionForm";
	}*/


	/**
	 * 导出
	 * @author xuchen
	 * @date 2018/11/06 10:10
	 * @param
	 * @return
	 */
	@RequestMapping(value = "export", method = RequestMethod.POST)
	public String exportFile(BizBuyingRequisition bizBuyingRequisition, HttpServletRequest request,
							 HttpServletResponse response, RedirectAttributes redirectAttributes) {
		// 导出完毕提示的消息
		String msg = "";
		//记录日志操作
		String startOperation="开始进行请购单数据导出操作！";
		String endOperation="请购单数据导出操作结束！";
		User user = UserUtils.getUser();
		try {

			String fileNamePrefix = DateUtils.getDate("yyyyMMddHHmmss");// 导出文件名前缀
			List<String> fileNames = new ArrayList<String>(); // 存放生成的文件名称
			String exportDir = FileUtils.path(Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL + user.getId()
					+ "/files/exportFiles/" + DateUtils.getDate("yyyy-MM-dd") + "/");
			String filePath = exportDir + fileNamePrefix + "/";// 导出文件子目录
			if (!new File(filePath).exists()) {
				new File(filePath).mkdirs();
			}
			String zipFileName = fileNamePrefix + ".zip";// 压缩文件名称
			String zipFilePath = exportDir + zipFileName;// 压缩文件路径
			// 根据查询条件查询
			Page<BizBuyingRequisitionDetail> page = new Page<BizBuyingRequisitionDetail>();
			// 需要导出的数据总数目
			int dataSize = 0;
			try {
				// 获取商品列表的导出总条数
				List<BizBuyingRequisitionDetail> buyingRequisitionDetails = bizBuyingRequisitionDetailService.
						findListByParent(bizBuyingRequisition);
				dataSize = buyingRequisitionDetails.size();
			} catch (Exception e) {
				log.info("获取导出的数据总数目失败！失败信息：" + e.getMessage());
				LogUtils.saveLog(request, null, e, "获取导出的数据总数目失败！");
			}
			if (dataSize == 0) {
				msg = "导出失败！失败信息：导出数据为空";
				addMessage(redirectAttributes, "导出失败！失败信息：导出数据为空");
				log.info("导出失败！失败信息：导出数据为空");
				LogUtils.saveLog(request, user.getName() + "导出失败！失败信息：导出数据为空");
				return "redirect:"+Global.getAdminPath()+"/biz/bizBuyingRequisition/?repage";
			} else {// 5000数据分一个文件
				int fileSize = StringUtils.isBlank(Global.getConfig("exportExcel.fileSize")) ? 5000
						: Integer.parseInt(Global.getConfig("exportExcel.fileSize"));
				int fileNo = dataSize / fileSize + 1;
				for (int i = 1; i <= fileNo; i++) {
					page = bizBuyingRequisitionDetailService.findPageByParent(
							new Page<BizBuyingRequisitionDetail>(i, fileSize),
							bizBuyingRequisition);
					String fileName = fileNamePrefix + "-" + String.valueOf(i) + ".csv";
					fileNames.add(fileName);
					// 创建csv文件
					new ExportCSV(BizBuyingRequisitionDetail.class, 1).setDataList(page.getList()).writeFile(filePath + fileName);
				}
				System.out.println("需要压缩的文件所在目录：" + filePath);
				System.out.println("压缩文件所在目录：" + exportDir);
				System.out.println("压缩文件名称：" + zipFilePath);

				log.info(startOperation);
				log.info("操作人：" + UserUtils.getUser().getName());
				log.info("预计导出数据共" + dataSize + "条");

				FileUtils.zipFiles(filePath, "", zipFilePath);

				FileUtils.delFile(filePath);
				msg = "导出成功！共导出数据：" + dataSize + "条。" + "文件只保留" + Global.getConfig("userfiles.life") + "天，请尽快到“"
						+ "<a href='" + request.getContextPath() + Global.getAdminPath()
						+ "/../static/ckfinder/ckfinder.html' style='color: white'>我的面板-文件管理</a>" + "”中下载！";
				addMessage(redirectAttributes,
						"导出成功！共导出数据：" + dataSize + "条。" + "文件只保留" + Global.getConfig("userfiles.life") + "天，请尽快到“"
								+ "<a href='" + request.getContextPath() + Global.getAdminPath()
								+ "/../static/ckfinder/ckfinder.html' style='color: white'>我的面板-文件管理</a>" + "”中下载！");
				log.info(endOperation);
				LogUtils.saveLog(request, user.getName() + "导出信息" + dataSize + "条");
			}
		} catch (Exception e) {
			msg = "导出失败！失败信息：" + e.getMessage();
			addMessage(redirectAttributes, "导出失败！失败信息：" + e.getMessage());
			log.info("导出失败！失败信息：" + e.getMessage());
			LogUtils.saveLog(request, null, e, user.getName() + "导出失败！");
		}
		return "redirect:"+Global.getAdminPath()+"/biz/bizBuyingRequisition/?repage";
	}

}